package com.world.tg.shiro;

import com.world.tg.dao.UserDao;
import com.world.tg.pojo.UserLogin;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserDao userDao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        // 获取用户提交的用户认证信息
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        UserLogin userLogin = userDao.login(username);

        // 如果用户不存在抛出异常
        if (userLogin == null) throw new UnknownAccountException();

        // 封装认证信息并返回
        ByteSource byteSource = ByteSource.Util.bytes(userLogin.getSalt());

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                userLogin.getUsername(),
                userLogin.getPassword(),
                byteSource,
                getName()
        );
        return info;
    }
}
